package csc.fresher.app;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

import javax.faces.context.FacesContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import csc.fresher.dao.impl.SystemUserDaoImpl;
import csc.fresher.entity.SystemRecordLogin;
import csc.fresher.view.SystemLoginManageBean;
import csc.fresher.view.SystemUserLogout;

@WebListener
public class SessionListener implements HttpSessionListener {
	@Override
	public void sessionCreated(HttpSessionEvent event) {

		try {
			SystemUserLogout.hasLogout = false;
			System.out
					.println("Session Created: " + event.getSession().getId());

			System.out.printf("Session ID %s created at %s%n", event
					.getSession().getId(), new Date());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		try {
			System.out.println("Session Destroyed: "
					+ event.getSession().getId());

			System.out.printf("Session ID %s destroyed at %s%n", event
					.getSession().getId(), new Date());

			if (SystemUserLogout.hasLogout == false) {
				SystemRecordLogin systemRecordLogin = new SystemRecordLogin();
				systemRecordLogin.setBeginTime(SystemLoginManageBean.beginTime);
				systemRecordLogin.setSystemUserID(SystemLoginManageBean.userID);
				systemRecordLogin.setEndTime(new Timestamp(System
						.currentTimeMillis()));

				SystemUserDaoImpl systemUserService = new SystemUserDaoImpl();
				systemUserService.createRecordLogin(systemRecordLogin);

			} else {
				try {
					FacesContext.getCurrentInstance().getExternalContext()
							.redirect("/csc_final/templates3/Logon.jsf");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}